import axios from 'axios'
import { Toast } from 'vant'
/* 封装axios基地址 */
const instance = axios.create({
  baseURL: 'http://toutiao.itheima.net',
  timeout: 10000 //设置网络超时
})
import { settoKen, gettoKen, removetoKen } from '../utils/token'
import router from '../router/index'
// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    if (gettoKen()) {
      config.headers.Authorization = `Bearer ${gettoKen().token}`
    }
    return config
  },
  function (error) {
    // 对请求错误做些什么
    console.log(error)
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    return response
  },
  async function (error) {
    console.log(error)
    if (error.response.status == 401) {
      if (gettoKen()) {
        try {
          let res = await axios({
            url: 'http://toutiao.itheima.net/v1_0/authorizations',
            mothod: 'put',
            headers: {
              Authorization: `Bearer ${gettoKen().refresh_token}`
            }
          })
          let newToken = gettoKen() //先取出旧的token
          newToken.token = res.data.data.token //更新token
          settoKen(newToken) //存入更新的token
          //继续发送之前的请求信息
          return instance(error.config)
        } catch (error) {
          Toast.fail('请重新登录')
          //移除token
          removetoKen()
          //跳转登录页
          router.push('/login')
        }
      } else {
        Toast.fail('请重新登录')
        router.push('/login')
      }
    } else {
      //不是401报错，不给处理
    }
    return Promise.reject(error)
  }
)
export default instance
